package com.boot.service.impl;

import com.boot.dao.JdbcTemplatePostgisImpl;
import com.boot.entity.GpsInfo;
import com.boot.service.GpsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by xudi on 2/9/16.
 */
@Service
public class GpsServiceImpl implements GpsService {

    @Autowired
    JdbcTemplatePostgisImpl jdbcTemplatePostgis;

    @Override
    public Boolean updateGpsInfo(Integer userId, String jwd) {
        String updateSql = "update building_gps_info_test set jwd=ST_Transform(ST_GeomFromText('POINT("+jwd+")', 4326),2163)," +
                "dt=current_timestamp where building_id="+userId;
        if (jdbcTemplatePostgis.executeUpdate(updateSql) == 0) {
            System.out.println("error!!");
            return false;
        }
        return true;
    }

    @Override
    public Boolean addGpsInfo(Integer userId, String jwd) {
        String isExistSql = "select count(*) from building_gps_info_test where building_id=" + userId;
        if (!jdbcTemplatePostgis.isExist(isExistSql)) {
            String insertSql = "insert into building_gps_info(building_id,jwd,dt) " +
                    "values(" + userId + ",ST_Transform(ST_GeomFromText('POINT(" + jwd + ")', 4326),2163),current_timestamp);";
            if (jdbcTemplatePostgis.executeUpdate(insertSql) == 0) {
                System.out.println("error!!");
                return false;
            }else {
                return true;
            }

        }
        return false;
    }

    @Override
    public List<GpsInfo> queryGpsInfo(String jwd) {
        String querySql = "select *,ST_Distance(jwd, ST_Transform(ST_GeomFromText('POINT("+jwd+")', 4326), 2163)) " +
                "from building_gps_info_test order by jwd <-> ST_Transform(ST_GeomFromText('POINT("+jwd+")',4326), 2163) limit 20;";
        return jdbcTemplatePostgis.executeQuery(querySql);
    }
}
